package com.github.shiqiyue.app.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.shiqiyue.app.api.sapi.req.user.UserPageReq;
import com.github.shiqiyue.app.common.enums.EnableEnum;
import com.github.shiqiyue.app.config.security.sapi.SapiLoginUser;
import com.github.shiqiyue.app.modules.sys.entity.*;
import com.github.shiqiyue.app.modules.sys.mapper.UserMapper;
import com.github.shiqiyue.app.modules.sys.service.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wenyao.wu
 * @since 2018-10-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IRolePermissionService roleMenuService;

    @Autowired
    private IUserPermissionService userMenuService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRoleService roleService;

    /***
     * 管理员的用户名
     */
    public static final String ADMIN_USERNAME = "admin";

    @Override
    public User findByName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User.NAME, name);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Integer countByName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User.NAME, name);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer countByName(String name, Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User.NAME, name);
        queryWrapper.ne(User.ID, id);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public IPage<User> page(UserPageReq query) {
        return baseMapper.userPage(new Page(query.getCurrent(), query.getSize()), query);
    }

    @Override
    public List<String> getPermissionsByUser(User user) {
        Long roleId = user.getRoleId();
        Long userId = user.getId();
        if (roleId == null || userId == null) {
            return Lists.newArrayList();
        }
        Set<String> permissionsSet = Sets.newHashSet();
        // 如果是管理员，默认获取全部权限
        if (ADMIN_USERNAME.equals(user.getName())) {
            List<Permission> permissions = permissionService.list();
            if (CollectionUtils.isNotEmpty(permissions)) {
                permissions.forEach((item) -> {
                    permissionsSet.add(item.getCode());
                });
            }
            return Lists.newArrayList(permissionsSet);
        }
        Role role = roleService.getById(roleId);
        if (role != null && EnableEnum.ABLE.equals(role.getEnable())) {
            permissionsSet.add(role.getCode());
            List<RolePermission> roleMenuList = roleMenuService.findByRoleId(roleId);
            if (CollectionUtils.isNotEmpty(roleMenuList)) {
                roleMenuList.forEach((item) -> {
                    permissionsSet.add(item.getPermission().getCode());
                });
            }
        }
        List<UserPermission> userMenuList = userMenuService.findByUserId(userId);
        if (CollectionUtils.isNotEmpty(userMenuList)) {
            userMenuList.forEach((item) -> {
                permissionsSet.add(item.getPermission().getCode());
            });
        }
        return Lists.newArrayList(permissionsSet);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = findByName(username);
        SapiLoginUser loginUser = null;
        if (user != null) {
            loginUser = new SapiLoginUser();
            loginUser.setUser(user);
            loginUser.setPermissions(getPermissionsByUser(user));
            // 如果权限未空，则添加匿名的全权限
            if (CollectionUtils.isEmpty(loginUser.getPermissions())) {
                loginUser.getPermissions().add("anonymous");
            }
            loginUser.setAuthorities(loginUser.getPermissions().stream().map((item) -> {
                return new SimpleGrantedAuthority(item);
            }).collect(Collectors.toList()));

        }
        return loginUser;
    }
}
